package com.anhtuan.reminder.tasks;

import java.util.Calendar;

import com.anhtuan.reminder.services.NotifyService;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class StartAlarmTask implements Runnable {
	
	// The date selected for alarm
	private final Calendar calendar;
	// Time to repeat the alarm
	private final long intervalMillis;
	private final boolean repeat;
	// System alarm manager
	private final AlarmManager alarmManager;
	// Context to retrieve the alarm manager
	private final Context context;
	// Id to identify the alarm
	private final int requestCode;
	
	public StartAlarmTask(int requestCode, Context context, Calendar calendar, boolean repeat, long intervalMillis) {
		this.requestCode = requestCode;
		this.context = context;
		this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		this.calendar = calendar;
		this.repeat = repeat;
		this.intervalMillis = intervalMillis;
	}
	
	@Override
	public void run() {
		
		Intent intent = new Intent(context, NotifyService.class);
		intent.putExtra(NotifyService.INTENT_START, true);
		intent.putExtra(NotifyService.INTENT_TASK_ID, requestCode);
		
		PendingIntent pendingIntent = PendingIntent.getService(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		
		// Set an alarm
		if (repeat) {
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervalMillis, pendingIntent);
		} else {
			alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
		}
	}

}
